package com.yjx.controller;

import com.yjx.dto.LoginUser;
import com.yjx.pojo.User;
import com.yjx.service.UserService;
import com.yjx.util.Result;
import com.yjx.dto.RegisterUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<LoginUser> login(
            @RequestParam String usernameOrEmail,
            @RequestParam String password
    ){
        LoginUser loginUser = userService.login(usernameOrEmail, password);
        // 根据结果返回响应
        if (loginUser == null) {
            return Result.fail("用户名或密码错误", 400); // 失败：状态码400
        }
        return Result.success(loginUser); // 成功：返回用户信息
    }

    @PostMapping("/createUser")
    public Result<String> createUser(@RequestBody RegisterUser registerUser) {
        // 调用 Service 时，从 DTO 中获取参数
        return userService.createUser(
                registerUser.getUserName(),
                registerUser.getUserEmail(),
                registerUser.getUserPasswordHash()
        );
    }

    /**
     * 查询所有用户
     */
    @GetMapping("/getAllUsers")
    public Result<Map<String, Object>> getAllUsers(
            // 前端传递的参数（与你之前的 getAllRepair 接口参数一致）
            @RequestParam(value = "userId",required = false) Integer userId,
            @RequestParam(value = "searchKeyword", required = false) String searchKeyword,
            @RequestParam(value = "pageNum", required = false) Integer pageNum,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "sortField", required = false) String sortField,
            @RequestParam(value = "sortOrder", required = false) String sortOrder)
    {
        Map<String, Object> data = userService.getAllUsers(userId, searchKeyword, pageNum, pageSize, sortField, sortOrder);
        return Result.success(data);  // 响应格式：{code:200, msg:"success", data:{...}}
    }

    //修改用户
    @PostMapping("/updateUser")
    public Result<String> updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }

    //删除用户
    @DeleteMapping("/delete/{userId}")
    public Result<?> delete(@PathVariable Integer userId) {
        int result = userService.deleteUserByUserId(userId);
        if (result > 0) {
            return Result.success("删除成功");
        } else {
            return Result.fail("删除失败，配件不存在",404);
        }
    }
}
